package com.ebrothers.isns;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.ebrothers.isns.common.JsonConverter;
import com.ebrothers.isns.common.Params;
import com.ebrothers.isns.common.Utils;
import com.ebrothers.isns.dao.AnswerDAO;
import com.ebrothers.isns.dao.DAOException;
import com.ebrothers.isns.vo.Answer;
import com.ebrothers.isns.vo.ResultVo;

/**
 * Servlet implementation class AnswerQuestion
 */
public class AnswerQuestion extends HttpServlet {
	private static final Logger logger = Logger.getLogger(AnswerQuestion.class);
	private static final long serialVersionUID = 1L;

	private AnswerDAO answerDAO;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public AnswerQuestion() {
		super();
		answerDAO = new AnswerDAO();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String qId = request.getParameter(Params.Q_ID);
		String aName = request.getParameter(Params.U_NAME);
		String aBody = request.getParameter(Params.A_BODY);
		String aPos = request.getParameter(Params.A_POS);
		logger.info("[AnswerQuestion] qId=" + qId + ", aName=" + aName
				+ ", aBody=" + aBody + ", aPos=" + aPos);
		long result = -1;
		if (aName != null && aBody != null) {
			Answer answer = new Answer();
			answer.setBody(aBody);
			answer.getOwner().setName(aName);
			answer.getQuestion().setId(Long.parseLong(qId));
			answer.setTriggerLocation(Utils.stringToLocation(aPos));
			try {
				result = answerDAO.insertAnswer(answer);
			} catch (DAOException e) {
				logger.error("GOT AN ERROR!", e);
				throw new ServletException(e);
			}
		}
		ResultVo resultVo = new ResultVo();
		resultVo.setResult(String.valueOf(result));
		String json = JsonConverter.beanToJson(resultVo);
		PrintWriter out = response.getWriter();
		logger.info("[AnswerQuestion] result=" + json);
		out.write(json);
		out.flush();
		out.close();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}
